#pragma once

#include "pch.h"

#include <filesystem>
#include <fstream>
#include <sstream>

namespace ym
{
    class FileUtils
    {
    public:
        /*
         * @brief 从文件中获取字符串
         * @param path 文件路径
         */
        static std::string getStringFromFile(const std::filesystem::path& path)
        {
            try
            {

                std::ifstream file(path, std::ios::binary | std::ios::ate);
                if (!file.is_open())
                {
                    throw std::system_error(errno, std::generic_category(), "Can't open file: " + path.string());
                }
                const auto size = file.tellg();
                if (size == -1)
                {
                    throw std::system_error(errno, std::generic_category(), "Can't get file size: " + path.string());
                }

                std::string content;
                content.resize(static_cast<size_t>(size));

                // 移动回文件开头
                file.seekg(0);

                // 直接读取到字符串内存
                if (!file.read(content.data(), static_cast<std::streamsize>(size)))
                {
                    throw std::system_error(errno, std::generic_category(), "Can't read file: " + path.string());
                }

                return content;
            }
            catch (const std::exception& e)
            {
                std::cerr << e.what() << std::endl;
                return "";
            }
        }

    private:
        FileUtils() = delete;
    };
} // namespace ym